package be.redo.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import be.redo.model.entities.AirlineCompany;

@Repository
public class AirlineCompanyDAOImpl implements AirlineCompanyDAO {

	private EntityManager entityManager;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public void create(AirlineCompany instance) {
		try {
			entityManager.persist(instance);
		} catch (RuntimeException ex) {
			entityManager.clear();
			throw ex;
		}
	}

	@Override
	public AirlineCompany read(long id) {
		return entityManager.find(AirlineCompany.class, id);
	}

	@Override
	public void update(AirlineCompany instance) {
		try {
			entityManager.merge(instance);
			entityManager.flush();
		} catch (RuntimeException ex) {
			entityManager.clear();
			throw ex;
		}
	}

	@Override
	public void delete(long id) {
		AirlineCompany instance = entityManager.find(AirlineCompany.class, id);
		if (instance != null) {
			entityManager.remove(instance);
			entityManager.flush();
		}
	}

	@Override
	public List<AirlineCompany> findAll() {
		TypedQuery<AirlineCompany> query = entityManager.createNamedQuery(
				"findAllAirlineCompanies", AirlineCompany.class);
		return query.getResultList();
	}

	@Override
	public int count() {
		TypedQuery<Number> query = entityManager.createNamedQuery(
				"findAantalAirlineCompanies", Number.class);
		return (query.getSingleResult()).intValue();
	}

	public List<AirlineCompany> findAirlineCompaniesByNameLike(String name) {
		TypedQuery<AirlineCompany> query = entityManager.createNamedQuery(
				"findAirlineCompaniesByNameLike", AirlineCompany.class);
		query.setParameter("name", name);
		return query.getResultList();
	}

}
